/**
 * Copyright (C) 2010 Lynx S.p.A. <lucio.benfante@gmail.com>
 *
 * This file is part of Ternion Web Application.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.lynxspa.ternion.web.beans;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * A validator for the authorities checkboxes of a UserBean.
 * 
 * @author Lucio Benfante
 */
public class UserBeanAuthoritiesValidator implements Validator {

    public boolean supports(Class clazz) {
        return UserBean.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        UserBean userBean = (UserBean) target;
        boolean noneChecked = true;
        for (AuthorityCheckBox authorityCheckBox : userBean.getAuthorityCheckBoxes()) {
            if (authorityCheckBox.isChecked()) {
                noneChecked = false;
                break;
            }
        }
        if (noneChecked) {
            errors.rejectValue("authorityCheckBoxes", "noCheckedAuthorities",
                    "At least one authority must be checked!");
        }
    }
}
